package com.iqiao.common.db.aop;

import com.iqiao.common.db.annotation.DataSource;
import com.iqiao.common.db.datasource.DynamicDataSourceHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.aop.BeforeAdvice;

import java.lang.reflect.Method;

/**
 * Created by flt on 2017/11/2.
 */
public class DataSourceAspect implements BeforeAdvice {

    public void before(JoinPoint point) {
        Object target = point.getTarget();
        System.out.println(target.toString());
        String method = point.getSignature().getName();
        System.out.println(method);
        Class<?> clazz = target.getClass();
        Class<?>[] parameterTypes = ((MethodSignature) point.getSignature())
                .getMethod().getParameterTypes();
        try {
            Method m = clazz.getMethod(method, parameterTypes);
            System.out.println(m.getName());
            if (m.isAnnotationPresent(DataSource.class)) {
                DataSource data = m.getAnnotation(DataSource.class);
                DynamicDataSourceHolder.putDataSource(data.value());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
